(function() {
	
	jQuery._ajax = function(options) {
		var defaults = {
			type : 'GET',
			url : '',
			async : true,
			dataType : 'json',
			complete : function() {},
			beforeSend : function() {},
			success : function() {},
			error : function() {}
		};
		var settings = $.extend(defaults, options);
		$.ajax({
			async : settings.async,
			type : settings.type,
			url : options.url,
			data : settings.data,
			dataType : settings.dataType,
			complete : settings.complete,
			beforeSend : options.beforeSend,
			success : settings.success,
			error : settings.error
		});
	};
	
	jQuery._get = function(options) {
		options.type = 'GET';
		$._ajax(options);
	};

	jQuery._post = function(options) {
		options.type = 'POST';
		$._ajax(options);
	};
	
	/**
	 * 解析参数[a=11&b=22&c=33]转成对象
	 */
	jQuery.parseParams = function(params) {
		var obj = {}, data;
		var reg_params = /([^&=]+)=([\w\W]*?)(&|$|#)/g;
		while ((data = reg_params.exec(params)) != null) {
			obj[data[1]] = data[2];
		}
		return obj;
	};
	
	/**
	 * 解析URL中的参数，转成对象
	 */
	jQuery.parseUrlParams = function (url) {
		var reg_url = /^[^\?]+\?([\w\W]+)$/, reg_params = /([^&=]+)=([\w\W]*?)(&|$|#)/g, arr_url = reg_url.exec(url), obj = {};
		if (arr_url && arr_url[1]) {
			var str_params = arr_url[1], result;
			while ((result = reg_params.exec(str_params)) != null) {
				obj[result[1]] = result[2];
			}
		}
		return obj;
	};
	
	/**
	 * 获取URL的参数
	 */
	jQuery.getUrlParam = function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		var r = window.location.search.substr(1).match(reg);
		if (r != null)
			return unescape(r[2]);
		return null;
	};
	
	/**
	 * 拼接参数
	 */
	jQuery.matchParams = function(param, key) {
		var paramStr = "";
		if (param instanceof String || param instanceof Number || param instanceof Boolean) {
			paramStr += "&" + key + "=" + encodeURIComponent(param);
		} else {
			$.each(param, function(i) {
				var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
				paramStr += '&' + $.matchParams(this, k);
			});
		}
		return paramStr.substr(1);
	};
	
})(jQuery);

function add(title, url, name, width, height) {
	formSubmitDialog(title, url, name, width, height);
}

function update(title, url, name, width, height) {
	var grid = $('#' + name),  rowsData = grid.datagrid('getSelections');
	if (!rowsData || rowsData.length != 1) {
		var message = '想要' + title + (title ? ',' : '') + '请选择一条且只能选择一条数据！';
		msgTip(message);
		return;
	}
	var idField = grid.attr('idfield') + '';
	formSubmitDialog(title, idFieldMatchUrl(idField, url, rowsData), name, width, height);
}

function idFieldMatchUrl(idField, url, rowsData) {
	var ids = idField.split(',');
	for(var i = 0; i < ids.length; i++) {
		url += '&' + ids[i] + '=' + rowsData[0][ids[i]];
	}
	return url;
}

/**
 * 表单提交窗口
 * @param title
 * @param url
 * @param width
 * @param height
 */
function formSubmitDialog(title, url, name, width, height) {
	width = width ? width : 600;
	height = height ? height : 300;
	$.dialog({
		content: 'url:' + url,
		cache:false,
		lock: true,
		title : title,
		width: width,
	    height: height,
	    ok: function(){
	    	var iframe = this.iframe.contentWindow;
	    	$('button[name="hideSubmitBtn"]', iframe.document).click();
	        return false;
	    },
	    cancelVal: '关闭',
	    cancel: true /*为true等价于function(){}*/
	});
}

/**
 * 弹出框
 * @param title
 * @param url
 * @param width
 * @param height
 */
function dialog(title, url, width, height) {
	width = width ? width : 600;
	height = height ? height : 300;
	$.dialog({
		content: 'url:' + url,
		lock: true,
		cache:false,
		title : title,
		width: width,
	    height: height,
	    ok: function(){
	    	var iframe = this.iframe.contentWindow;
	    	$('button[name="hideSubmitBtn"]', iframe.document).click();
	        return false;
	    },
	    cancelVal: '关闭',
	    cancel: true /*为true等价于function(){}*/
	});
}

/**
 * 打开窗口
 * @param title
 * @param url
 * @param width
 * @param height
 */
function openWin(title, url, width, height) {
	width = width ? width : 600;
	height = height ? height : 300;
	$.dialog({
		content: 'url:' + url,
		lock: true,
		cache:false,
		title : title,
		width: width,
	    height: height,
	    cancelVal: '关闭',
	    cancel: true
	});
}

/**
 * 询问弹出框
 * @param url
 * @param message
 * @param name
 */
function doSubmitConfirm(url, message, name) {
	$.dialog.confirm(message, function() {
		doGridSubmit(url, name);
	}, function() {
	});
}

/**
 * 表格请求提交
 * @param url
 * @param name
 * @param data
 */
function doGridSubmit(url, name, subData) {
	if (!subData) {
		subData = $.parseUrlParams(url);
		url = url.indexOf('&') != -1 ? url.substring(0, url.indexOf('&')) : url;
	}
	$._post({
		url : url,
		data : subData,
		success : function(res) {
			if (res.status == '10000' || res.status == '10001'
					|| res.status == '10002' || res.status == '10003'
					|| res.status == '10004' || res.status == '10009'
					|| res.status == '10101' || res.status == '10102'
					|| res.status == '10103') {
				if (name) {
					eval(name + 'ReloadGridTable();');
				}
			}
			msgTip(res.message);
		}
	});
}

/**
 * 右下角弹出消息提示框
 * @param message
 */
function msgTip(message) {
	$.messager.show({
		title : '提示信息',
		msg : message,
		timeout : 1000 * 3
	});
}

/**
 * 添加标签
 * @param title
 * @param url
 * @param icon
 */
function addTab(title, url, icon) {
	window.top.$.messager.progress({
		text : '页面加载中....',
		interval : 300
	});
	window.top.$('#main-content-easyui-tabs').tabs({
		onClose : function(title, index) {
			window.top.$.messager.progress('close');
		}
	});
	if (window.top.$('#main-content-easyui-tabs').tabs('exists', title)) {
		window.top.$('#main-content-easyui-tabs').tabs('select', title);
	} else {
		window.top.$('#main-content-easyui-tabs').tabs('add', {
			title : title,
			content : '<iframe src="' + url + '" frameborder="0" style="border:0;width:100%;height:99.6%;" />',
			closable : true,
			iconCls : icon
		});
	}
}

/**
 * 对Date的扩展，将 Date 转化为指定格式的String 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 * 可以用 1-2 个占位符 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) eg: (new
 * Date()).format("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423 (new
 * Date()).format("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 (new
 * Date()).format("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 (new
 * Date()).format("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 (new
 * Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, 									//月份         
		"d+" : this.getDate(), 											//日         
		"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, 	//小时         
		"H+" : this.getHours(), 										//小时         
		"m+" : this.getMinutes(), 										//分         
		"s+" : this.getSeconds(), 										//秒         
		"q+" : Math.floor((this.getMonth() + 3) / 3), 					//季度         
		"S" : this.getMilliseconds() 									//毫秒         
	};
	var week = {
		"0" : "/u65e5",
		"1" : "/u4e00",
		"2" : "/u4e8c",
		"3" : "/u4e09",
		"4" : "/u56db",
		"5" : "/u4e94",
		"6" : "/u516d"
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}